package com.xsomnus.network_programming.netty.udp.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/7/24 0024 9:56
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final String[] DICT = {
            "只要功夫深,铁杵磨成针",
            "旧时王谢堂前燕,飞入寻常百姓家",
            "洛阳亲友如相问,一片冰心在玉壶",
            "一寸光阴一寸金,寸金难买寸光阴",
            "老骥伏枥,志在千里.烈士暮年,壮心不已!"
    };

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String request = msg.content().toString(StandardCharsets.UTF_8);
        System.out.println("收到的请求：" + request);
        if ("give me a quote".equals(request)) {
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("query result: " + next(), StandardCharsets.UTF_8), msg.sender()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    private String next() {
        int quoteId = ThreadLocalRandom.current().nextInt(DICT.length);
        return DICT[quoteId];
    }
}
